package com.ultrapower.ctool.xn_app;

import android.content.Intent;
import android.graphics.Color;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.ultrapower.ctool.ConfUtils;
import com.ultrapower.ctool.core.CustomApplication;
import com.ultrapower.ctool.http.BaseActivity;
import com.ultrapower.ctool.model.RegisterRolePirVO;
import com.ultrapower.ctool.utils.InstanceUtil;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import okhttp3.FormBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

public class ChangeXunChaResultActivity extends BaseActivity implements View.OnClickListener {
    private EditText bh_change_xc_result;//编号
    private EditText xcbh_change_xc_result;//巡查表编号
    private Spinner xcname_change_xc_result;//项目名称
    private Spinner xcresult_change_xc_result;//巡查项结果
    private EditText detail_change_xc_result;//结果描述
    private Button save_change_xc_result;
    private Button cancle_change_xc_result;
    private CustomApplication application;
    private Gson gson = new Gson();
    private Map<String, EditText> textMap = new HashMap<String, EditText>();
    private Map<String, Spinner> spinnerMap = new HashMap<String, Spinner>();
    private ArrayAdapter<RegisterRolePirVO> mnameAdapter;
    private ArrayAdapter<RegisterRolePirVO> mresultAdapter;
    private Map<String, Map<String, Object>> resultMap;
    private static List<RegisterRolePirVO> mnames = new ArrayList<RegisterRolePirVO>();
    private static List<RegisterRolePirVO> mresults = new ArrayList<RegisterRolePirVO>();
    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case 1:
                    Toast.makeText(getApplicationContext(), "修改成功", Toast.LENGTH_SHORT).show();
                    // TODO: 2017/5/21 修改null
                    //Intent intent = new Intent(ChangeWangGeHandleActivity.this, WangGeHandleActivity.class);

                    //startActivity(intent);
                    finish();
                    break;
                case 0:
                    Toast.makeText(getApplicationContext(), "系统出现异常", Toast.LENGTH_SHORT).show();
                    break;
            }
        }
    };
    private AdapterView.OnItemSelectedListener OnCatSpinnerCL = new AdapterView.OnItemSelectedListener() {
        public void onItemSelected(AdapterView<?> parent, View view, int pos, long id) {
            ((TextView) parent.getChildAt(0)).setTextColor(Color.BLACK);
            ((TextView) parent.getChildAt(0)).setTextSize(18);
        }

        public void onNothingSelected(AdapterView<?> parent) {

        }
    };

    static {
        mresults.add(new RegisterRolePirVO("", ""));
        mresults.add(new RegisterRolePirVO("1", "达标"));
        mresults.add(new RegisterRolePirVO("2", "不达标"));
        mnames.add(new RegisterRolePirVO("", ""));
        mnames.add(new RegisterRolePirVO("1", "燃气安全"));
        mnames.add(new RegisterRolePirVO("2", "电源安全"));
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_change_xun_cha_result);
        init();
        application = (CustomApplication) getApplication();

        // TODO: 2017/5/21  根据ID查询后台数据
        Intent intent = getIntent();
        getWangGeInfo(intent.getStringExtra("mid"));
    }

    private void getWangGeInfo(final String mid) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                Response response = null;
                Request request = null;
                try {
                    OkHttpClient client = new OkHttpClient();
                    RequestBody requestBody = new FormBody.Builder()
                            .add("userId", String.valueOf(application.getLoginUser().getLogin_id()))
                            .build();
                    request = new Request.Builder().url(ConfUtils.SERVICE_URL + "inspect/xcxmUpdate/c_aj_xcxm-" + mid).post(requestBody).build();
                    response = client.newCall(request).execute();
                    if (response.isSuccessful()) {//成功
                        String result = response.body().string();
                        System.out.println(result);
                        resultMap = gson.fromJson(result, Map.class);
                        System.out.println(resultMap);
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                for (Map.Entry<String, Object> entry : resultMap.get("result").entrySet()) {
                                    if (textMap.get(entry.getKey()) != null) {
                                        textMap.get(entry.getKey()).setText(entry.getValue().toString());
                                    }
                                    if ("mname".equals(entry.getKey())) {
                                        for (int i = 0; i < mnames.size(); i++) {
                                            if (mnames.get(i).getId().equals(entry.getValue().toString())) {
                                                xcname_change_xc_result.setSelection(i);
                                                break;
                                            }
                                        }
                                    }
                                    if ("itemvalue".equals(entry.getKey())) {
                                        for (int i = 0; i < mresults.size(); i++) {
                                            if (mresults.get(i).getId().equals(entry.getValue().toString())) {
                                                xcresult_change_xc_result.setSelection(i);
                                                break;
                                            }
                                        }
                                    }
                                }
                            }
                        });

                    } else {
                        Message message = new Message();
                        message.what = 0;
                        handler.sendMessage(message);
                    }
                } catch (Exception e) {
                    Message message = new Message();
                    message.what = 0;
                    handler.sendMessage(message);
                    e.printStackTrace();
                } finally {
                    if (response != null) response.close();

                }
            }
        }).start();
    }

    protected void init() {
        bh_change_xc_result = (EditText) findViewById(R.id.bh_change_xc_result);
        textMap.put("mid", bh_change_xc_result);
        xcbh_change_xc_result = (EditText) findViewById(R.id.xcbh_change_xc_result);
        textMap.put("cid", xcbh_change_xc_result);

        xcname_change_xc_result = (Spinner) findViewById(R.id.xcname_change_xc_result);
        spinnerMap.put("mname", xcname_change_xc_result);
        xcresult_change_xc_result = (Spinner) findViewById(R.id.xcresult_change_xc_result);
        spinnerMap.put("itemvalue", xcname_change_xc_result);
        detail_change_xc_result = (EditText) findViewById(R.id.detail_change_xc_result);
        textMap.put("mcaption", detail_change_xc_result);

        save_change_xc_result = (Button) findViewById(R.id.save_change_xc_result);
        cancle_change_xc_result = (Button) findViewById(R.id.cancle_change_xc_result);
        save_change_xc_result.setOnClickListener(this);
        cancle_change_xc_result.setOnClickListener(this);
        //将可选内容与ArrayAdapter连接起来
        mnameAdapter = new ArrayAdapter<RegisterRolePirVO>(this, android.R.layout.simple_spinner_item, mnames);
        //设置下拉列表的风格
        mnameAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        //将adapter 添加到spinner中
        xcname_change_xc_result.setAdapter(mnameAdapter);
        //添加事件Spinner事件监听
        xcname_change_xc_result.setOnItemSelectedListener(OnCatSpinnerCL);
        //设置默认值
        //xcname_change_xc_result.setVisibility(View.VISIBLE);

        //将可选内容与ArrayAdapter连接起来
        mresultAdapter = new ArrayAdapter<RegisterRolePirVO>(this, android.R.layout.simple_spinner_item, mresults);
        //设置下拉列表的风格
        mresultAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        //将adapter 添加到spinner中
        xcresult_change_xc_result.setAdapter(mresultAdapter);
        //添加事件Spinner事件监听
        xcresult_change_xc_result.setOnItemSelectedListener(OnCatSpinnerCL);
        //设置默认值
        //xcresult_change_xc_result.setVisibility(View.VISIBLE);
    }

    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.save_change_xc_result:

                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        Response response = null;
                        try {
                            OkHttpClient client = new OkHttpClient();
                            //String _id = new DBHelper(changVo).queryBycn(entry.getValue().getText().toString());
                            FormBody.Builder builder = new FormBody.Builder()
                                    .add("userId", String.valueOf(application.getLoginUser().getLogin_id()));
                            for (Map.Entry<String, EditText> entry : textMap.entrySet()) {

                                    resultMap.get("result").put(entry.getKey(), entry.getValue().getText().toString());

                            }
                            for (Map.Entry<String, Spinner> entry : spinnerMap.entrySet()) {
                                resultMap.get("result").put(entry.getKey(), ((RegisterRolePirVO) entry.getValue().getSelectedItem()).getId());
                            }
                            for (Map.Entry<String, Object> entry : resultMap.get("result").entrySet()) {
                                    builder.add(entry.getKey(), (String) entry.getValue());

                            }
                            RequestBody requestBody = builder.build();
                            Request request = new Request.Builder().url(ConfUtils.SERVICE_URL + "form/doUpdate/c_aj_xcxm").post(requestBody).build();
                            response = client.newCall(request).execute();
                            if (response.isSuccessful()) {//成功
                                String result = response.body().string();
                                System.out.println("result:" + result);
                                Map<String, Object> resultMap = gson.fromJson(result, Map.class);
                                if ((boolean) resultMap.get("success")) {
                                    Message message = new Message();
                                    message.what = 1;
                                    handler.sendMessage(message);
                                }else{
                                    Message message = new Message();
                                    message.what = 0;
                                    handler.sendMessage(message);
                                }
                            } else {
                                Message message = new Message();
                                message.what = 0;
                                handler.sendMessage(message);
                            }
                        } catch (Exception e) {
                            Message message = new Message();
                            message.what = 0;
                            handler.sendMessage(message);
                            e.printStackTrace();
                        } finally {
                            if (response != null) response.close();

                        }
                    }
                }).start();
                break;
            case R.id.cancle_change_xc_result:
                finish();
                break;
        }
    }
}
